import {cookies} from "next/headers";


const TOKEN_AGE = 3600;
const TOKEN_NAME = "auth-token";
const TOKEN_REFRESH_TOKEN = "auth-refresh-token";

// 获取 CookieStore（单例模式）
async function getCookieStore() {
    return await cookies();
}

export async function getToken() {
    // api request
    const cookieStore = await getCookieStore();
    const myAuthToken = cookieStore.get(TOKEN_NAME);
    return myAuthToken?.value;
}

export async function getRefreshToken() {
    // api request
    const cookieStore = await getCookieStore();
    const myAuthToken = cookieStore.get(TOKEN_REFRESH_TOKEN);
    return myAuthToken?.value;
}

export async function setToken(authToken) {
    // login
    const cookieStore = await getCookieStore();
    cookieStore.set({
        name: TOKEN_NAME,
        value: authToken,
        httpOnly: true,
        sameSite: "strict",
        secure: process.env.NODE_ENV !== "development",
        maxAge: TOKEN_AGE
    });
}

export async function setRefreshToken(authRefreshToken) {
    // login
    const cookieStore = await getCookieStore();
    cookieStore.set({
        name: TOKEN_REFRESH_TOKEN,
        value: authRefreshToken,
        httpOnly: true,
        sameSite: "strict",
        secure: process.env.NODE_ENV !== "development",
        maxAge: TOKEN_AGE
    });
}

export async function deleteToken() {
    // logout
    const cookieStore = await getCookieStore();
    cookieStore.delete(TOKEN_REFRESH_TOKEN);
    return cookieStore.delete(TOKEN_NAME);
}